package mrusanov.ui.battle

import actions.{ActionList, Action}
import javax.swing.{SwingUtilities, Timer}
import java.awt.event.{ActionEvent, ActionListener}
import collection.immutable.Queue

object ActionsExecutor extends ActionListener {
  private var queue:Queue[Action] = Queue()
  private var lastTime = -1L

  val timer = new Timer(50, this)


  def startTimer() {
    timer.start()
  }

  def stopTimer() {
    timer.stop()
  }

  def actionPerformed(e:ActionEvent) {
    if (lastTime == -1) {
      lastTime = System.currentTimeMillis()
      return
    }

    val difference = System.currentTimeMillis() - lastTime
    lastTime = System.currentTimeMillis()

    val actionsList = new ActionList(queue.toList)
    actionsList.update(difference.toInt)

    this.synchronized {
      queue = queue.dropWhile(_.isCompleted)
    }
  }

  def addActions(actions:List[Action]) {
    this.synchronized {
      queue ++= actions
    }
  }
}
